package com.shanpin.shebao.web.module.user;

import com.shanpin.core.utils.DateUtil;
import com.shanpin.shebao.model.user.SBUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.shanpin.shebao.web.db.AppDbRepository;
import com.shanpin.shebao.web.module.user.model.TUser;

import java.util.List;

@Repository
public class UserDao {
	
	@Autowired
	private AppDbRepository jdbc;
	
	/** 检查手机号是否已经存在  true: 存在 */
	protected boolean checkPhone(String phone) {
		String sql = "SELECT u_id FROM t_user WHERE phone=? limit 1";
		int uid = jdbc.queryInt(sql, phone);
		return uid == 0 ? false : true;
	}
	
	protected TUser queryby(String phone) {
		String sql = "SELECT * FROM t_user where phone = ? limit 1";
		TUser user = jdbc.queryT(sql, TUser.detailMapper, phone);
		return user;
	}
	
	/**
	 * 参保用户的身份证号
	 * @param sbuId
	 * @return
	 */
	protected String getId_card(int sbuId, int uid) {
		String sql = "SELECT id_card FROM t_sb_user where id=? AND u_id=?";
		return jdbc.queryString(sql, sbuId, uid);
	}

	/**
	 * 身份证图片信息为空的参保人.
	 * @return
	 */
	public List<SBUser> getNoImgSbUser() {
		int hm = Integer.parseInt(DateUtil.currentStr("Hmm"));
		if (930 == hm) {
			return jdbc.query(SBUser.card_name_imgF+" WHERE id_card_img='' ORDER BY id DESC",
					SBUser.card_name_img_mapper);
		}
		return jdbc.query(SBUser.card_name_imgF+" WHERE reg_channel='51SBGJ' AND id_card_img=''",
				SBUser.card_name_img_mapper);
	}

	public void updateIdcardImg(int id, String id_card_img) {
		jdbc.update("UPDATE t_sb_user SET id_card_img=? WHERE id=?", id_card_img, id);
	}
	
	protected boolean  checkIdfaExists(String idfa, String appid, String advertiser) {
		int id = jdbc.queryInt("SELECT id FROM t_user_device_flag WHERE deviceId=? LIMIT 1", idfa);
		if (id == 0) {
			id = jdbc.queryInt("SELECT id FROM t_sb_advertiser WHERE idfa=? LIMIT 1", idfa);
			if (id == 0) {
				String sql = "INSERT INTO t_sb_advertiser (`idfa`,`appid`, `advertiser`, `gen_time`, `update_time` ) VALUES (?,?,?, NOW(), NOW())";
				jdbc.update(sql, idfa, appid, advertiser);
				return false;
			}
		}
		return true;
	}
	
	protected boolean  confirmIdfa(String idfa, String callbackUrl) {
		return jdbc.update("UPDATE t_sb_advertiser SET confirm2=1, callbackUrl=?,"
				+ " update_time=NOW() WHERE idfa=?", callbackUrl, idfa);
	}
	
	@Transactional
	public boolean addAdData(String idfa, String appid, String advertiser, String callback) {
		boolean exists = checkIdfaExists(idfa, appid, advertiser);
		if (exists) {
			return true;
		}
		return confirmIdfa(idfa, callback);
	}
}
